<template>
  <div class="search-box" :class="searchBoxClass">
    <!-- 搜索输入框 -->
    <div class="search-input-wrapper">
      <el-input
        v-model="searchKeyword"
        :placeholder="placeholder"
        :size="size"
        :clearable="clearable"
        :disabled="disabled"
        class="search-input"
        @input="handleInput"
        @keyup.enter="handleSearch"
        @focus="handleFocus"
        @blur="handleBlur"
        @clear="handleClear"
      >
        <template #prefix>
          <el-icon class="search-icon">
            <Search />
          </el-icon>
        </template>
        <template #suffix v-if="showAdvanced">
          <el-button
            text
            size="small"
            @click="toggleAdvanced"
            class="advanced-btn"
          >
            高级
          </el-button>
        </template>
      </el-input>
      
      <!-- 搜索按钮 -->
      <el-button
        v-if="showSearchButton"
        type="primary"
        :size="size"
        :loading="loading"
        @click="handleSearch"
        class="search-button"
      >
        搜索
      </el-button>
    </div>
    
    <!-- 搜索建议下拉框 -->
    <div
      v-if="showSuggestions && suggestions.length > 0"
      class="search-suggestions"
      v-click-outside="hideSuggestions"
    >
      <div class="suggestions-header" v-if="suggestionsTitle">
        {{ suggestionsTitle }}
      </div>
      <ul class="suggestions-list">
        <li
          v-for="(suggestion, index) in suggestions"
          :key="index"
          class="suggestion-item"
          :class="{ active: activeSuggestionIndex === index }"
          @click="selectSuggestion(suggestion)"
          @mouseenter="activeSuggestionIndex = index"
        >
          <el-icon v-if="suggestion.icon" class="suggestion-icon">
            <component :is="suggestion.icon" />
          </el-icon>
          <div class="suggestion-content">
            <div class="suggestion-title" v-html="highlightKeyword(suggestion.title || suggestion)"></div>
            <div class="suggestion-desc" v-if="suggestion.description">
              {{ suggestion.description }}
            </div>
          </div>
          <div class="suggestion-type" v-if="suggestion.type">
            {{ suggestion.type }}
          </div>
        </li>
      </ul>
      <div class="suggestions-footer" v-if="showMoreSuggestions">
        <el-button text size="small" @click="viewAllSuggestions">
          查看全部结果
        </el-button>
      </div>
    </div>
    
    <!-- 高级搜索面板 -->
    <div
      v-if="showAdvancedPanel"
      class="advanced-search-panel"
      v-click-outside="hideAdvanced"
    >
      <div class="panel-header">
        <span class="panel-title">高级搜索</span>
        <el-button text size="small" @click="hideAdvanced">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      
      <div class="panel-content">
        <!-- 分类筛选 -->
        <div class="filter-group" v-if="categories.length > 0">
          <label class="filter-label">分类</label>
          <el-select
            v-model="advancedFilters.category"
            placeholder="选择分类"
            clearable
            class="filter-select"
          >
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </div>
        
        <!-- 难度筛选 -->
        <div class="filter-group" v-if="difficulties.length > 0">
          <label class="filter-label">难度</label>
          <el-select
            v-model="advancedFilters.difficulty"
            placeholder="选择难度"
            clearable
            class="filter-select"
          >
            <el-option
              v-for="difficulty in difficulties"
              :key="difficulty.value"
              :label="difficulty.label"
              :value="difficulty.value"
            />
          </el-select>
        </div>
        
        <!-- 价格筛选 -->
        <div class="filter-group" v-if="showPriceFilter">
          <label class="filter-label">价格</label>
          <el-radio-group v-model="advancedFilters.priceType" class="price-radio-group">
            <el-radio label="all">全部</el-radio>
            <el-radio label="free">免费</el-radio>
            <el-radio label="paid">付费</el-radio>
          </el-radio-group>
        </div>
        
        <!-- 时间筛选 -->
        <div class="filter-group" v-if="showTimeFilter">
          <label class="filter-label">时间范围</label>
          <el-date-picker
            v-model="advancedFilters.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="time-picker"
          />
        </div>
        
        <!-- 排序方式 -->
        <div class="filter-group">
          <label class="filter-label">排序方式</label>
          <el-select
            v-model="advancedFilters.sortBy"
            placeholder="选择排序方式"
            class="filter-select"
          >
            <el-option label="相关度" value="relevance" />
            <el-option label="最新" value="newest" />
            <el-option label="最热" value="popular" />
            <el-option label="评分" value="rating" />
            <el-option label="价格从低到高" value="price_asc" />
            <el-option label="价格从高到低" value="price_desc" />
          </el-select>
        </div>
      </div>
      
      <div class="panel-footer">
        <el-button @click="resetAdvancedFilters">重置</el-button>
        <el-button type="primary" @click="handleAdvancedSearch">搜索</el-button>
      </div>
    </div>
    
    <!-- 搜索历史 -->
    <div
      v-if="showHistory && searchHistory.length > 0 && isFocused && !searchKeyword"
      class="search-history"
      v-click-outside="hideHistory"
    >
      <div class="history-header">
        <span class="history-title">搜索历史</span>
        <el-button text size="small" @click="clearHistory">
          清空
        </el-button>
      </div>
      <ul class="history-list">
        <li
          v-for="(item, index) in searchHistory.slice(0, 8)"
          :key="index"
          class="history-item"
          @click="selectHistory(item)"
        >
          <el-icon class="history-icon"><Clock /></el-icon>
          <span class="history-text">{{ item }}</span>
          <el-button
            text
            size="small"
            @click.stop="removeHistory(index)"
            class="remove-btn"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </li>
      </ul>
    </div>
    
    <!-- 热门搜索 -->
    <div
      v-if="showHotSearch && hotSearches.length > 0 && isFocused && !searchKeyword"
      class="hot-search"
      v-click-outside="hideHotSearch"
    >
      <div class="hot-header">
        <span class="hot-title">热门搜索</span>
      </div>
      <div class="hot-tags">
        <el-tag
          v-for="(item, index) in hotSearches"
          :key="index"
          class="hot-tag"
          :type="index < 3 ? 'danger' : 'info'"
          @click="selectHotSearch(item)"
        >
          {{ item }}
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Close, Clock } from '@element-plus/icons-vue'
import { debounce } from '@/utils'

// Props
const props = defineProps({
  // 占位符文本
  placeholder: {
    type: String,
    default: '搜索课程、考试...'
  },
  // 输入框大小
  size: {
    type: String,
    default: 'default',
    validator: (value) => ['large', 'default', 'small'].includes(value)
  },
  // 是否可清空
  clearable: {
    type: Boolean,
    default: true
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 是否显示搜索按钮
  showSearchButton: {
    type: Boolean,
    default: false
  },
  // 是否显示高级搜索
  showAdvanced: {
    type: Boolean,
    default: true
  },
  // 是否显示搜索建议
  showSuggestions: {
    type: Boolean,
    default: true
  },
  // 是否显示搜索历史
  showHistory: {
    type: Boolean,
    default: true
  },
  // 是否显示热门搜索
  showHotSearch: {
    type: Boolean,
    default: true
  },
  // 是否显示价格筛选
  showPriceFilter: {
    type: Boolean,
    default: true
  },
  // 是否显示时间筛选
  showTimeFilter: {
    type: Boolean,
    default: false
  },
  // 分类选项
  categories: {
    type: Array,
    default: () => []
  },
  // 难度选项
  difficulties: {
    type: Array,
    default: () => [
      { label: '初级', value: 'beginner' },
      { label: '中级', value: 'intermediate' },
      { label: '高级', value: 'advanced' }
    ]
  },
  // 初始搜索关键词
  modelValue: {
    type: String,
    default: ''
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits([
  'update:modelValue',
  'search',
  'advanced-search',
  'suggestion-select',
  'focus',
  'blur'
])

const router = useRouter()

// 响应式数据
const searchKeyword = ref(props.modelValue)
const isFocused = ref(false)
const showAdvancedPanel = ref(false)
const activeSuggestionIndex = ref(-1)
const suggestions = ref([])
const searchHistory = ref(JSON.parse(localStorage.getItem('searchHistory') || '[]'))
const hotSearches = ref([
  'Vue.js', 'React', 'JavaScript', 'Python', 'Java',
  '前端开发', '后端开发', '数据结构', '算法', '机器学习'
])

// 高级搜索筛选条件
const advancedFilters = ref({
  category: '',
  difficulty: '',
  priceType: 'all',
  timeRange: null,
  sortBy: 'relevance'
})

// 计算属性
const searchBoxClass = computed(() => ({
  [`search-box--${props.size}`]: true,
  'search-box--focused': isFocused.value,
  'search-box--disabled': props.disabled
}))

const suggestionsTitle = computed(() => {
  return suggestions.value.length > 0 ? '搜索建议' : ''
})

const showMoreSuggestions = computed(() => {
  return suggestions.value.length > 5
})

// 监听器
watch(() => props.modelValue, (newValue) => {
  searchKeyword.value = newValue
})

watch(searchKeyword, (newValue) => {
  emit('update:modelValue', newValue)
})

// 防抖搜索建议
const debouncedGetSuggestions = debounce(async (keyword) => {
  if (!keyword.trim()) {
    suggestions.value = []
    return
  }
  
  try {
    // 这里应该调用搜索建议 API
    // const response = await searchApi.getSuggestions(keyword)
    // suggestions.value = response.data
    
    // 模拟搜索建议
    suggestions.value = [
      { title: `${keyword} 基础教程`, type: '课程', icon: 'Reading' },
      { title: `${keyword} 进阶课程`, type: '课程', icon: 'Reading' },
      { title: `${keyword} 认证考试`, type: '考试', icon: 'Document' },
      { title: `${keyword} 实战项目`, type: '项目', icon: 'Folder' }
    ]
  } catch (error) {
    console.error('获取搜索建议失败:', error)
    suggestions.value = []
  }
}, 300)

// 方法
const handleInput = (value) => {
  if (props.showSuggestions) {
    debouncedGetSuggestions(value)
  }
}

const handleSearch = () => {
  if (!searchKeyword.value.trim()) return
  
  // 添加到搜索历史
  addToHistory(searchKeyword.value.trim())
  
  // 隐藏建议和面板
  hideSuggestions()
  hideAdvanced()
  
  // 触发搜索事件
  emit('search', {
    keyword: searchKeyword.value.trim(),
    filters: {}
  })
  
  // 跳转到搜索结果页
  router.push({
    path: '/search',
    query: { q: searchKeyword.value.trim() }
  })
}

const handleAdvancedSearch = () => {
  if (!searchKeyword.value.trim()) return
  
  // 添加到搜索历史
  addToHistory(searchKeyword.value.trim())
  
  // 隐藏面板
  hideAdvanced()
  
  // 触发高级搜索事件
  emit('advanced-search', {
    keyword: searchKeyword.value.trim(),
    filters: { ...advancedFilters.value }
  })
  
  // 跳转到搜索结果页
  const query = {
    q: searchKeyword.value.trim(),
    ...advancedFilters.value
  }
  
  router.push({
    path: '/search',
    query
  })
}

const handleFocus = () => {
  isFocused.value = true
  emit('focus')
}

const handleBlur = () => {
  // 延迟隐藏，避免点击建议时立即隐藏
  setTimeout(() => {
    isFocused.value = false
    emit('blur')
  }, 200)
}

const handleClear = () => {
  suggestions.value = []
  activeSuggestionIndex.value = -1
}

const toggleAdvanced = () => {
  showAdvancedPanel.value = !showAdvancedPanel.value
}

const hideAdvanced = () => {
  showAdvancedPanel.value = false
}

const hideSuggestions = () => {
  suggestions.value = []
  activeSuggestionIndex.value = -1
}

const hideHistory = () => {
  // 历史记录在失去焦点时自动隐藏
}

const hideHotSearch = () => {
  // 热门搜索在失去焦点时自动隐藏
}

const selectSuggestion = (suggestion) => {
  const keyword = suggestion.title || suggestion
  searchKeyword.value = keyword
  emit('suggestion-select', suggestion)
  handleSearch()
}

const selectHistory = (item) => {
  searchKeyword.value = item
  handleSearch()
}

const selectHotSearch = (item) => {
  searchKeyword.value = item
  handleSearch()
}

const addToHistory = (keyword) => {
  if (!keyword || searchHistory.value.includes(keyword)) return
  
  searchHistory.value.unshift(keyword)
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10)
  }
  
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

const removeHistory = (index) => {
  searchHistory.value.splice(index, 1)
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
}

const resetAdvancedFilters = () => {
  advancedFilters.value = {
    category: '',
    difficulty: '',
    priceType: 'all',
    timeRange: null,
    sortBy: 'relevance'
  }
}

const viewAllSuggestions = () => {
  handleSearch()
}

const highlightKeyword = (text) => {
  if (!searchKeyword.value.trim()) return text
  
  const keyword = searchKeyword.value.trim()
  const regex = new RegExp(`(${keyword})`, 'gi')
  return text.replace(regex, '<mark>$1</mark>')
}

// 键盘事件处理
const handleKeydown = (event) => {
  if (!suggestions.value.length) return
  
  switch (event.key) {
    case 'ArrowDown':
      event.preventDefault()
      activeSuggestionIndex.value = Math.min(
        activeSuggestionIndex.value + 1,
        suggestions.value.length - 1
      )
      break
    case 'ArrowUp':
      event.preventDefault()
      activeSuggestionIndex.value = Math.max(
        activeSuggestionIndex.value - 1,
        -1
      )
      break
    case 'Enter':
      event.preventDefault()
      if (activeSuggestionIndex.value >= 0) {
        selectSuggestion(suggestions.value[activeSuggestionIndex.value])
      } else {
        handleSearch()
      }
      break
    case 'Escape':
      hideSuggestions()
      break
  }
}

// 添加键盘事件监听
nextTick(() => {
  document.addEventListener('keydown', handleKeydown)
})
</script>

<style lang="scss" scoped>
.search-box {
  position: relative;
  width: 100%;
  
  &--focused {
    z-index: 1000;
  }
  
  .search-input-wrapper {
    display: flex;
    gap: 8px;
    
    .search-input {
      flex: 1;
      
      :deep(.el-input__wrapper) {
        border-radius: 20px;
        transition: all 0.3s ease;
        
        &:hover,
        &.is-focus {
          box-shadow: 0 0 0 1px var(--el-color-primary) inset;
        }
      }
      
      .search-icon {
        color: var(--el-text-color-placeholder);
      }
      
      .advanced-btn {
        color: var(--el-color-primary);
        font-size: 12px;
        padding: 0 4px;
      }
    }
    
    .search-button {
      border-radius: 20px;
      padding: 0 20px;
    }
  }
  
  // 搜索建议样式
  .search-suggestions {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-light);
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    z-index: 1001;
    margin-top: 4px;
    
    .suggestions-header {
      padding: 8px 16px;
      font-size: 12px;
      color: var(--el-text-color-placeholder);
      border-bottom: 1px solid var(--el-border-color-lighter);
    }
    
    .suggestions-list {
      list-style: none;
      margin: 0;
      padding: 0;
      max-height: 300px;
      overflow-y: auto;
      
      .suggestion-item {
        display: flex;
        align-items: center;
        padding: 8px 16px;
        cursor: pointer;
        transition: background-color 0.3s ease;
        
        &:hover,
        &.active {
          background: var(--el-fill-color-light);
        }
        
        .suggestion-icon {
          margin-right: 8px;
          color: var(--el-text-color-placeholder);
        }
        
        .suggestion-content {
          flex: 1;
          
          .suggestion-title {
            font-size: 14px;
            color: var(--el-text-color-primary);
            
            :deep(mark) {
              background: var(--el-color-primary-light-8);
              color: var(--el-color-primary);
              padding: 0;
            }
          }
          
          .suggestion-desc {
            font-size: 12px;
            color: var(--el-text-color-regular);
            margin-top: 2px;
          }
        }
        
        .suggestion-type {
          font-size: 11px;
          color: var(--el-text-color-placeholder);
          background: var(--el-fill-color);
          padding: 2px 6px;
          border-radius: 10px;
        }
      }
    }
    
    .suggestions-footer {
      padding: 8px 16px;
      text-align: center;
      border-top: 1px solid var(--el-border-color-lighter);
    }
  }
  
  // 高级搜索面板样式
  .advanced-search-panel {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-light);
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    z-index: 1001;
    margin-top: 4px;
    
    .panel-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      .panel-title {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
    }
    
    .panel-content {
      padding: 16px;
      
      .filter-group {
        margin-bottom: 16px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .filter-label {
          display: block;
          font-size: 13px;
          color: var(--el-text-color-regular);
          margin-bottom: 6px;
        }
        
        .filter-select {
          width: 100%;
        }
        
        .price-radio-group {
          display: flex;
          gap: 16px;
        }
        
        .time-picker {
          width: 100%;
        }
      }
    }
    
    .panel-footer {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      padding: 12px 16px;
      border-top: 1px solid var(--el-border-color-lighter);
    }
  }
  
  // 搜索历史样式
  .search-history {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-light);
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    z-index: 1001;
    margin-top: 4px;
    
    .history-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 16px;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      .history-title {
        font-size: 12px;
        color: var(--el-text-color-placeholder);
      }
    }
    
    .history-list {
      list-style: none;
      margin: 0;
      padding: 0;
      
      .history-item {
        display: flex;
        align-items: center;
        padding: 8px 16px;
        cursor: pointer;
        transition: background-color 0.3s ease;
        
        &:hover {
          background: var(--el-fill-color-light);
        }
        
        .history-icon {
          margin-right: 8px;
          color: var(--el-text-color-placeholder);
          font-size: 14px;
        }
        
        .history-text {
          flex: 1;
          font-size: 14px;
          color: var(--el-text-color-primary);
        }
        
        .remove-btn {
          opacity: 0;
          transition: opacity 0.3s ease;
        }
        
        &:hover .remove-btn {
          opacity: 1;
        }
      }
    }
  }
  
  // 热门搜索样式
  .hot-search {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-light);
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    z-index: 1001;
    margin-top: 4px;
    
    .hot-header {
      padding: 8px 16px;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      .hot-title {
        font-size: 12px;
        color: var(--el-text-color-placeholder);
      }
    }
    
    .hot-tags {
      padding: 12px 16px;
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      
      .hot-tag {
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-1px);
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .search-box {
    .search-input-wrapper {
      flex-direction: column;
      gap: 8px;
      
      .search-button {
        width: 100%;
      }
    }
    
    .advanced-search-panel {
      .panel-content {
        .price-radio-group {
          flex-direction: column;
          gap: 8px;
        }
      }
    }
    
    .hot-search {
      .hot-tags {
        .hot-tag {
          font-size: 12px;
        }
      }
    }
  }
}
</style>